package cn.gson.springboot.model.service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;

import cn.gson.springboot.model.dao.AdviceDao;
import cn.gson.springboot.model.dao.AdviceDetailsDao;
import cn.gson.springboot.model.dao.ApplyHospitalDao;
import cn.gson.springboot.model.dao.BedDao;
import cn.gson.springboot.model.dao.CashMoneyDao;
import cn.gson.springboot.model.dao.ClinicCardDAO;
import cn.gson.springboot.model.dao.DayAcountDao;
import cn.gson.springboot.model.dao.DrugDao;
import cn.gson.springboot.model.dao.HealAppointmentDao;
import cn.gson.springboot.model.dao.HealProjectDao;
import cn.gson.springboot.model.dao.HealthDAO;
import cn.gson.springboot.model.dao.IllnessRecordDao;
import cn.gson.springboot.model.dao.InhosptialRegDao;
import cn.gson.springboot.model.dao.LookillnessDAO;
import cn.gson.springboot.model.dao.OpreArrangeDao;
import cn.gson.springboot.model.dao.OpreaArrangeRecordDao;
import cn.gson.springboot.model.dao.OutHospitalDao;
import cn.gson.springboot.model.dao.PatientRoom;
import cn.gson.springboot.model.dao.PfInhospitalStorageDao;
import cn.gson.springboot.model.dao.PublicDurgDao;
import cn.gson.springboot.model.dao.PublicdurgDetailDao;
import cn.gson.springboot.model.dao.ReturnMoneyDao;
import cn.gson.springboot.model.dao.SectionDAO;
import cn.gson.springboot.model.mapper.AdviceDetailsMappers;
import cn.gson.springboot.model.mapper.AdviceMappers;
import cn.gson.springboot.model.mapper.ApplyHospitalMappers;
import cn.gson.springboot.model.mapper.BedMappers;
import cn.gson.springboot.model.mapper.CashMoneyMappers;
import cn.gson.springboot.model.mapper.ClinicCardMapper;
import cn.gson.springboot.model.mapper.DayAccountMappers;
import cn.gson.springboot.model.mapper.DrugRoomMappers;
import cn.gson.springboot.model.mapper.DrugstorageMapper;
import cn.gson.springboot.model.mapper.HealthMappers;
import cn.gson.springboot.model.mapper.HospitalRegMappers;
import cn.gson.springboot.model.mapper.IllnessRecordMappers;
import cn.gson.springboot.model.mapper.InhospitalstorageMapper;
import cn.gson.springboot.model.mapper.OpreArrangeMappers;
import cn.gson.springboot.model.mapper.ReturnMoneyMappers;
import cn.gson.springboot.model.mapper.SickRoomMappers;
import cn.gson.springboot.model.pojos.Bed;
import cn.gson.springboot.model.pojos.CashMoney;
import cn.gson.springboot.model.pojos.ClinicCard;
import cn.gson.springboot.model.pojos.DayAccount;
import cn.gson.springboot.model.pojos.DoctoradviceDetail;
import cn.gson.springboot.model.pojos.DoctorsAdvice;
import cn.gson.springboot.model.pojos.Drug;
import cn.gson.springboot.model.pojos.Health;
import cn.gson.springboot.model.pojos.HealthAppointment;
import cn.gson.springboot.model.pojos.HealthMeal;
import cn.gson.springboot.model.pojos.HealthProject;
import cn.gson.springboot.model.pojos.IllnessRecord;
import cn.gson.springboot.model.pojos.InhospitalReg;
import cn.gson.springboot.model.pojos.LookIllness;
import cn.gson.springboot.model.pojos.OperationArrange;
import cn.gson.springboot.model.pojos.OperationRecord;
import cn.gson.springboot.model.pojos.OutHospital;
import cn.gson.springboot.model.pojos.PublicDurg;
import cn.gson.springboot.model.pojos.PublicdurgDetail;
import cn.gson.springboot.model.pojos.ReturnMoney;
import cn.gson.springboot.model.pojos.Section;
import cn.gson.springboot.model.pojos.SickRoom;
import cn.gson.springboot.model.vo.AdviceVo;
import cn.gson.springboot.model.vo.AppointmentVo;
import cn.gson.springboot.model.vo.DrugfyVo;

@Service
@Transactional(rollbackOn=Exception.class)
public class ApplyHospitalService {

	
	@Autowired
	private ApplyHospitalMappers applyMapper;//通知单mapper层
	
	@Autowired
	private InhosptialRegDao regdao;//住院登记dao层
	@Autowired
	private HospitalRegMappers hmap;//住院登记记录的mapper层
	
	@Autowired
	private ClinicCardMapper ccmapper;//医疗卡的mapper
	@Autowired
	private ClinicCardDAO ccdao;//医疗卡得dao层
	
	@Autowired
	private BedDao bdao;//床位dao层
	@Autowired
	private BedMappers bmapper;//床位mapper层
	
	@Autowired
	private PatientRoom roomdao;//病房的dao层
	@Autowired
	private SickRoomMappers  roommapper;//病房的mapper层
	
	@Autowired
	private CashMoneyDao mdao;//押金dao层
	
	@Autowired
	private ReturnMoneyDao rdao;//退费的dao层
	@Autowired
	private ReturnMoneyMappers rmapper;//退费的mapper层
	
	@Autowired
	private HealProjectDao hpdao;//体检项目dao层
	
	@Autowired
	private HealAppointmentDao apdao;//体检预约dao层
	
	@Autowired
	private OpreArrangeMappers anmapper;//手术安排表的mapper
	@Autowired
	private OpreArrangeDao andao;//手术安排的dao层
	
	@Autowired
	private OpreaArrangeRecordDao redao;//手术记录的dao层
	
	@Autowired
	private AdviceDao adao;//医嘱的dao层
	
	@Autowired
	private AdviceDetailsDao addao;//医嘱详情的dao层
	@Autowired
	private AdviceDetailsMappers admapper;//医嘱详情的mapper层
	
	@Autowired
	private DrugDao ddao;//药品的dao
	
	@Autowired
	private AdviceMappers amapper;//医嘱mapper
	@Autowired
	private AdviceDetailsMappers demapper;//医嘱详情mapper
	
	
	@Autowired
	private IllnessRecordDao illdao;//病程记录dao层
	@Autowired
	private IllnessRecordMappers illmapper;//病程记录mapper层
	
	@Autowired
	private DayAcountDao daydao;//日结单的dao层
	@Autowired
	private DayAccountMappers daymapper;//日结单的mapper层
	
	@Autowired
	private OutHospitalDao outdao;//出院的dao层
	
	@Autowired
	private HealthMappers hmapper;//体检mapper
	@Autowired
	private HealthDAO hdao;//体检的dao层
	
	@Autowired
	private SectionDAO sedao;//科室的dao层
	
	@Autowired
	private InhospitalstorageMapper kucunmapper;//住院药品库存
	
	@Autowired
	private PublicDurgDao padao;//请领表
	@Autowired
	private PublicdurgDetailDao paddao;//请领详情
	
	@Autowired
	private DrugRoomMappers drugmapper;//药房的mapper

	
	
	//查询药房库存的药品信息
	public JSONArray selecthospdrugkucun(String drugname,String drugtype) {
		return drugmapper.selecthospdrugkucun(drugname,drugtype);
	}
	
	/*
	 * 住院登记界面的功能的方法
	 * 
	 * */
	
	//打印小票
	public JSONArray selectapplyreceipt() {
		return applyMapper.selectapplyreceipt();
	}
	
	//根据已同意的通知状态查询
	public JSONArray findApplyByidReg(Integer applyid) {
		return applyMapper.findalppyByidReg(applyid);
	}
	
	//查询床位号所属的病房
	public JSONArray selectRoomBedByid(Integer roomid) {
		return roommapper.selectRoomBedByid(roomid);
	}
	
	//新增住院登记（登记表，押金表，床位表，医疗卡表）[从门诊新增]
	public void AddHospRegsiter(String cliniccardId,String clinicName,
			Integer hospdoctorname,String hospId,String sectionname,
			Integer hospnursename,Integer sickroomId,
			Integer bedId,BigDecimal cashMoney, String hospTime,String hospPeople) {
		
		//根据医疗卡号查询
		ClinicCard c = ccdao.findByhospcradid(cliniccardId);
		Integer c_id = c.getClinicId();
		
		//新增住院登记表
	    hmap.AddHospReg(hospId,c_id,hospdoctorname,hospnursename,hospPeople);
	    
	    //根据住院id查询
	    InhospitalReg inhospitalReg = regdao.findById(hospId).get();
	    
	    //根据病房id查询
	    SickRoom room = roomdao.findById(sickroomId).get();
	    
		//根据床位id查询得到床位租金
  		Bed bed = bdao.findById(bedId).get();
  		//床位租金
  		BigDecimal bedmoney = bed.getBedMoney();
  		//床位号
  		String bedno = bed.getBedNo();	    
	    //完善床位表
  		Bed b1 = new Bed();
  		b1.setBedId(bedId);
  		b1.setInhospitalReg(inhospitalReg);
  		b1.setBedNo(bedno);
  		b1.setBedMoney(bedmoney);
  		b1.setSickRoom(room);
  		b1.setBedState(1);//修改床位的状态
  		
  		bdao.save(b1);
  		
		//新增押金表
		CashMoney m = new CashMoney();
		m.setInhospitalReg(inhospitalReg);//（住院号）
		m.setCashTotalmoney(cashMoney);//总押金
		//修改押金表的余额，扣除床位租金的金额（用押金余额-租金）
		BigDecimal  money = cashMoney.subtract(bedmoney);
		m.setCashDmoney(money);
		m.setCashTime(null);
		m.setCashOperatorName(null);
		
		mdao.save(m);
		
		//新增退费表（状态为1时，是每次交押金的记录）
		ReturnMoney rm = new ReturnMoney();
		rm.setInhospitalReg(inhospitalReg);//住院号
		rm.setReturnmoneyMoney(cashMoney);//押金金额
		rm.setReturnmoneyState(1);
		rm.setReturnmoneyTime(null);
		
		rdao.save(rm);
		
	}
	
	//住院自主登记的方法
	public void AddHospReg(String clinicName,String cliniccardId, String clinicIdnumber,
			Integer clinicAge,String clinicAddress,String clinicTel,
			String clinicHandlename,BigDecimal clinicRemainmoney,String clinicSex,
			Integer hospdoctorname,Integer hospnursename,
			String hospId,Integer bedId,BigDecimal cashMoney,String hospPeople) {
		
		//新增医疗卡
		ccmapper.addcliniccard(cliniccardId, clinicName, clinicIdnumber,
				clinicAge, clinicSex, clinicTel, clinicAddress,
				"小花",new BigDecimal(0),-1);
		
		//根据医疗卡号查询
		ClinicCard c = ccdao.findByhospcradid(cliniccardId);
		Integer c_id = c.getClinicId();
		
		//新增住院登记表
	    hmap.AddHospReg(hospId,c_id,hospdoctorname,hospnursename,hospPeople);
	    
		
		//根据住院id查询
	    InhospitalReg inhospitalReg = regdao.findById(hospId).get();
	    
	    //根据床位id查询得到床位租金
	    Bed bed = bdao.findById(bedId).get();  		
	    //床位租金
  		BigDecimal bedmoney = bed.getBedMoney();
  		//床位号
  		String bedno = bed.getBedNo();
  		//床位所属的病房
  		SickRoom room = bed.getSickRoom();	    
	    //完善床位表
  		Bed b = new Bed();
  		b.setBedId(bedId);
  		b.setInhospitalReg(inhospitalReg);
  		b.setBedNo(bedno);
  		b.setBedMoney(bedmoney);
  		b.setSickRoom(room);
  		b.setBedState(1);//修改床位的状态
  		
  		bdao.save(b);
  		
		//新增押金表
		CashMoney m = new CashMoney();
		m.setInhospitalReg(inhospitalReg);//（住院号）
		m.setCashTotalmoney(cashMoney);//总押金
		//修改押金表的余额，扣除床位租金的金额（用押金余额-租金）
		BigDecimal  money = cashMoney.subtract(bedmoney);
		m.setCashDmoney(money);
		m.setCashTime(null);
		m.setCashOperatorName(null);
		
		mdao.save(m);
		
		//新增退费表（状态为1时，是每次交押金的记录）
		ReturnMoney rm = new ReturnMoney();
		rm.setInhospitalReg(inhospitalReg);//住院号
		rm.setReturnmoneyMoney(cashMoney);//押金金额
		rm.setReturnmoneyState(1);
		rm.setReturnmoneyTime(null);
		
		rdao.save(rm);
	}
	
	
	//根据住院登记id查询
	public InhospitalReg selectByhospid(String hospid) {
		if(regdao.existsById(hospid)) {
			return regdao.findById(hospid).get();
		}
		return null;
	}
	
	//根据病房的满人的情况新增床位(初始化病房的下拉列表)
	public JSONArray selectRoomAll() {
		return roommapper.selectRoomAll();
	}
	//安排床位
	public JSONArray selectRoomBedAll(Integer sid) {
		return roommapper.selectRoomBedAll(sid);
	}
	
	
	//根据床位的状态查询床位(初始化床位号的下拉列表)
	public JSONArray selectBedAll(){
		return bmapper.selectBedAll();
	}
	
	//新增退费表（状态为1时，是每次交押金的记录，状态为-1时，是出院时押金余额多退少补的记录）
	public void AddReturnMoney(ReturnMoney remoney) {
		rdao.save(remoney);
	}
	
	//住院登记登记的多表联合查询
	public JSONArray findhospRecored(String clinicname){
		return hmap.findRegRecord(clinicname);
	}
	
	
	/*
	 * 通知单界面的功能的方法
	 * 
	 * */
	
	//新增通知单
	public void AddApply(Integer lookillness_id,String applyuser) {
		applyMapper.AddApply(lookillness_id,applyuser);
	}
	
	//根据通知单id查询
	//通知单查询（通知单表，看诊表，医疗卡表，用户表[门诊医生]，科室表）
	public JSONArray findApplyById(Integer applyid) {
		return applyMapper.findapplyBystatus(applyid);
	}
	
	//修改通知单的状态
	public void updateApplyStatus(Integer applysatus,Integer applyid) {
		applyMapper.updateApplyStatusByApplyid(applysatus,applyid);
	}
	
	//通知单查询，通知单记录
	public  JSONArray findapplyrecordAll() {
		return applyMapper.findapplyrecordAll();
	}

	
	
	/*
	 * 
	 * 医生站的功能方法
	 * 
	 * */
	
	//查询药品【用于住院开立医嘱的药品信息】     
	public JSONArray selectHospDrugAll(String drugname,String drugtype) {
	    return kucunmapper.selectHospDrugAll(drugname, drugtype);
	} 
	
	//开立医嘱（新增医嘱表，医嘱详情）
	public String saveOrder(AdviceVo advvo) {
		//获取医嘱进行新增
		DoctorsAdvice advice = advvo.getAdvice();
		//获取住院登记进行新增
		InhospitalReg regentity = advvo.getReg();
		//获取看诊
		LookIllness lookentity = advvo.getLook();
		advice.setLookIllness(lookentity);
		//时间
 		advvo.getAdvice().setDocBegintime(new  Timestamp(new Date().getTime()));
 		advvo.getAdvice().setDocEndtime(new Timestamp(new Date().getTime()));
		//查询住院号
		InhospitalReg reg = regdao.findById(regentity.getHospId()).get();
		advice.setInhospitalReg(reg);
		adao.save(advice);
		
		//医嘱详情
		List<DoctoradviceDetail> details = advvo.getDetails();
		
		for (DoctoradviceDetail pur : details) {
			//添加订单信息
			pur.setDoctorsAdvice(advice);
			//查询药品
			Drug drug = ddao.findById(pur.getDrug().getDrugNumber()).get();
			//获取药品的类型
		    int typeid = drug.getType().getTypeId();
		    //获取药品的总金额
		    BigDecimal  tmoney = drug.getDrugRetailPrice();
		    Integer count = pur.getDocdetailsEverynnum();
		    BigDecimal new_count = new  BigDecimal(count);
		    
		    BigDecimal  zmoney = tmoney.multiply(new_count);//药品的总金额
			//重新赋值一下药品对象
			pur.setDrug(drug);
			addao.save(pur);
				
			//3是注射类的编号
			//如果是口服类的药，就要扣押金以及减少药房中的住院库存
			if(typeid!=3) {
				//1、修改医嘱的是否交钱和是否执行医嘱的状 
				//1、扣除押金
				CashMoney cash_Money = mdao.findCashmoneyBihospid(reg.getHospId());
				//新增押金表
				CashMoney m = new CashMoney();
				m.setCashId(cash_Money.getCashId());
				m.setInhospitalReg(reg);//（住院号）
				m.setCashTotalmoney(cash_Money.getCashTotalmoney());//总押金
				//获取押金的余额
				BigDecimal bmoney = cash_Money.getCashDmoney();
				BigDecimal ymoney = bmoney.subtract(zmoney);				
				if(ymoney.compareTo(new BigDecimal(0)) <= -150) {
					return "押金余额超出透支";
				}
				m.setCashDmoney(ymoney);
				m.setCashTime(cash_Money.getCashTime());
				m.setCashOperatorName(cash_Money.getCashOperatorName());
				mdao.save(m);
				
				//2、修改医嘱的状态
				amapper.updateAdviceMoneyStatus(advice.getDocadviceId());
				
				//3、生成执行医嘱表，日结表
				DayAccount  day = new DayAccount();
				day.setDayMoney(zmoney);
				day.setDayOpreator(reg.getHospPeople());
				day.setAccount(null);
				daydao.save(day);
				
				//4、新增病程记录
				IllnessRecord ill = new IllnessRecord();
				ill.setDayAccount(day);
				ill.setDoctoradviceDetail(pur);
				ill.setIllOperator(reg.getHospPeople());
				ill.setInhospitalReg(reg);
				ill.setIllDrugcount(String.valueOf(pur.getDocdetailsEverynnum()));
				ill.setIllHz(String.valueOf(pur.getDocdetailsEverynnum()));
				illdao.save(ill);
				
				//5、修改医嘱详情的状态，作为已执行
				admapper.updateAdviceDetailsSatus(1,pur.getDocdetailsId());
				
				//6、修改药房中的住院库存的库存数量
				//根据药品id找到所有药品批次
				JSONArray selectPici= drugmapper.selectInHosPiciBydrugNumber(pur.getDrug().getDrugNumber(),null);

			   for (int i = 0; i <= selectPici.size(); i++) {
				   	//每个药品的批次
			    	Integer inhospital_pici = selectPici.getJSONObject(i).getInteger("inhospital__pici");
			    	//得到每个药品对应批次的库存数量
		 		    JSONArray InHosdrugAmount = drugmapper.selectInHosPiciBydrugNumber(pur.getDrug().getDrugNumber(), inhospital_pici);
			    	Integer InhoseveryAmount = InHosdrugAmount.getJSONObject(0).getInteger("inhospital__storage_amount");
			    	//库存数量为零
			        if(InhoseveryAmount==0){
			        	continue;
			        }
			    	//批次查出来此药品库存数量>=药品数量
			        if(pur.getDocdetailsEverynnum()<=InhoseveryAmount){
			        	//修改药房库存
			        	drugmapper.updateInhospitalkucun(pur.getDocdetailsEverynnum(),pur.getDrug().getDrugNumber(), inhospital_pici);
			        	break;
			        }
			        //批次查出来此药品库存数量<=药品数量
			         if(pur.getDocdetailsEverynnum()>InhoseveryAmount){
			        	     //修改药房小库存
				        	 drugmapper.updateInhospitalkucun(pur.getDocdetailsEverynnum(),pur.getDrug().getDrugNumber(), inhospital_pici);
		 
			        }
			        	 continue;
			    }

				
			}
			
			//如果是注射类的药就扣除押金
			if(typeid==3) {
				CashMoney cashMoneys = mdao.findCashmoneyBihospid(reg.getHospId());
				//新增押金表
				CashMoney m = new CashMoney();
				m.setCashId(cashMoneys.getCashId());
				m.setInhospitalReg(reg);//（住院号）
				m.setCashTotalmoney(cashMoneys.getCashTotalmoney());//总押金
				//获取押金的余额
				BigDecimal bmoney = cashMoneys.getCashDmoney();
				
				BigDecimal ymoney = bmoney.subtract(zmoney);
				m.setCashDmoney(ymoney);
				m.setCashTime(cashMoneys.getCashTime());
				m.setCashOperatorName(cashMoneys.getCashOperatorName());
				mdao.save(m);
				
				//2、修改医嘱的状态
				amapper.updateAdviceMoneyStatus(advice.getDocadviceId());
				
			}
			
			
		}
		return "新增失败";

	}
	
	
	//查询医嘱的所有
	public JSONArray findAdviceAll() {
		return amapper.selectAdviceAll();
	}
	
	//根据医嘱编号查询医嘱详情
	public JSONArray selectAdviceDetailsAll(Integer docadviceid) {
		return demapper.selectAdviceDetailsAll(docadviceid);
	}
	
	//手术室的初始化
	public JSONArray selectOpreationRoomAll() {
		return anmapper.selectOpreateRoomAll();
	}
	
	//手术类型的初始化
	public JSONArray selectOpreationTypeAll(Integer oprid) {
		return anmapper.selectOpreateTypeAll(oprid);
	}
	
	
	//新增手术安排
	public String AddOpreArrange(Integer oproom,Integer hospdoctorname,
			Integer hospnursename,Integer optype,String hospid,
			String opreason,String starttime,String endtime,
			BigDecimal futruemoney,String dateday) {

		//把String类型的dateday转换成Date类型
	    String dateString = dateday;//获取传过来的值
	   //1、定义转换格式
	    SimpleDateFormat formatter  = new SimpleDateFormat("yyyy-MM-dd");
	    Date date = null;
		try {
			date = formatter.parse(dateString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	    String  dString = formatter.format(date);
	    Date data = java.sql.Date.valueOf(dString);		
		OperationArrange arrange = andao.selectArrangeTime(starttime,data,oproom);
		if(arrange != null) {
			return "此时间段已安排";
		}
		InhospitalReg inhospitalReg = regdao.findById(hospid).get();
		//扣除安排手术的预估金额
		CashMoney cashMoney = mdao.findCashmoneyBihospid(hospid);
	    //修改押金表的押金余额
		CashMoney m = new CashMoney();
		m.setCashId(cashMoney.getCashId());
		m.setInhospitalReg(inhospitalReg);
		m.setCashTotalmoney(cashMoney.getCashTotalmoney());
		//用押金余额  - 手术预估金额
		BigDecimal money = cashMoney.getCashDmoney().subtract(futruemoney);
		if(money.compareTo(new BigDecimal(0)) <= -150) {
			return "押金余额超出透支";
		}
		m.setCashDmoney(money);
		m.setCashOperatorName(cashMoney.getCashOperatorName());
		mdao.save(m);
		//新增手术安排表
		anmapper.AddOpreArrange(oproom, hospdoctorname, hospnursename,
				optype, hospid,opreason, starttime, endtime,
				futruemoney, data);
		return "成功";

	}
	
	//查询病例记录
	public JSONArray selectHospCase() {
		return hmap.selectHospCase();
	}
	 
	/*
	 * 
	 * 护士站的功能
	 * 
	 * */
	//初始化医疗卡
	public JSONArray selectnotAdviceByclinic() {
		return amapper.selectnotAdviceByclinic();
	}
	
	
	//医嘱核医嘱详情查询（得到领药的情况）
	public JSONArray selectAdviceDetailsBYclinic() {
		return amapper.selectAdviceDetailsBYclinic();
	}
	public JSONArray selectapplydrugAll() {
		return amapper.selectapplydrugAll();
	}
	//申请领药
	public String AddapplyDrug(DrugfyVo dvo) {
		//发药主表
		PublicDurg publicdurg = dvo.getPublicdurg();
		padao.save(publicdurg);
		List<PublicdurgDetail> publicdurgDetail = dvo.getPublicdurgdetail();
		for (PublicdurgDetail pd : publicdurgDetail) {
			pd.setPublicDurg(publicdurg);
			DoctoradviceDetail detail = addao.findById(pd.getDoctoradviceDetail().getDocdetailsId()).get();
			pd.setDoctoradviceDetail(detail);
			pd.setPdDetailsDate(new  Timestamp(new Date().getTime()));
			paddao.save(pd);
		}
		return "申请成功";
	}
	
	
	//新增病程记录【新增病程记录（日结表暂时未null），修改医嘱详情的状态】
	public void AddIllnessRecord(String hospId,Integer docdetailsId,Integer dayid,
			String illOperator,String illDrugcount,String illHz,
			Integer samallkucun,Integer drugno) {
		//新增病程记录
		illmapper.AddIllnessRecord(docdetailsId, dayid, hospId, illOperator, illDrugcount, illHz);
		
		//药品的用量
        Integer drugyl =  Integer.valueOf(illHz);       
    	//药品的数量
        Integer  drugeveryNumber  =  Integer.valueOf(illDrugcount);        
        if(drugeveryNumber==drugyl) {
        	//修改医嘱详情的状态，作为已执行
    		admapper.updateAdviceDetailsSatus(1,docdetailsId);
        }
		//减少库存
		//根据药品id找到所有药品批次
		JSONArray selectPici= drugmapper.selectInHosPiciBydrugNumber(drugno,null);
	   for (int i = 0; i <= selectPici.size(); i++) {
	    	 //每个药品的批次
	    	Integer inhospital_pici = selectPici.getJSONObject(i).getInteger("inhospital__pici");
	    	//得到每个药品对应批次的库存数量
 		    JSONArray InHosdrugAmount = drugmapper.selectInHosPiciBydrugNumber(drugno, inhospital_pici);
	    	Integer InhoseveryAmount = InHosdrugAmount.getJSONObject(0).getInteger("inhosp_samallstorage");
	    	//库存数量为零
	        if(InhoseveryAmount==0){
	        	continue;
	        }
	    	//批次查出来此药品库存数量>=药品数量
	        if(drugyl<=InhoseveryAmount){
	        	//修改药房库存
	        	drugmapper.updateHospsamllstorage(drugyl,drugno, inhospital_pici);
	        	break;
	        }
	        //批次查出来此药品库存数量<=药品数量
	         if(drugyl>InhoseveryAmount){
	        	     //修改药房小库存
		        	 drugmapper.updateHospsamllstorage(drugyl,drugno, inhospital_pici);
	        	 }
	        	 continue;
	        }
	}
	
	//查询未执行的医嘱
	public JSONArray selectNotAdviceDetails() {
		return amapper.selectNotAdviceDetails();
	}
	
	//病房和床位联合查询
	public JSONArray selectBedSickRoomAll() {
		return bmapper.selectBedSickRoomAll();
	}
	
	//新增修改医嘱详情
	public void AddAdviceDetails(DoctoradviceDetail details) {
		addao.save(details);
	}
	
	
	
	//查询病程记录
	public JSONArray selectNessRecordAll() {
		return illmapper.selectNessRecordAll();
	}
	
	//查询当天的病程记录
	public JSONArray selectTradayNessRecordAll() {
		return illmapper.selectTradayNessRecordAll();
	}
	
	//催缴押金
	public void  addpaymoney(String hospId,BigDecimal cashDmoney) {
		InhospitalReg inhospitalReg = regdao.findById(hospId).get();
		//根据住院号查询押金的主键
		CashMoney money = mdao.findCashmoneyBihospid(hospId);
		Integer cashid = money.getCashId();
		//获取总押金
		BigDecimal tmoney = money.getCashTotalmoney();
		String people=money.getCashOperatorName();
		//获取押金余额
		BigDecimal bmoney = money.getCashDmoney();
		//计算余额的绝对值
		BigDecimal balance = cashDmoney.add(bmoney);
		//计算总押金
		BigDecimal totalmoney = cashDmoney.add(tmoney);
		//催缴押金表（修改）
		CashMoney m = new CashMoney();
		m.setCashId(cashid);
		m.setInhospitalReg(inhospitalReg);//住院号
		m.setCashDmoney(balance);
		m.setCashTotalmoney(totalmoney);
		m.setCashOperatorName(people);
		m.setCashTime(null);
		mdao.save(m);
		
		//新增退费表（状态为1时，是每次交押金的记录）
		ReturnMoney rm = new ReturnMoney();
		rm.setInhospitalReg(inhospitalReg);//住院号
		rm.setReturnmoneyMoney(cashDmoney);//押金金额
		rm.setReturnmoneyState(1);
		rm.setReturnmoneyTime(null);
		rdao.save(rm);
		
	}
	
	//新增日结单
	public void addPayDay(String arr,String drugtotal,String dayOpreator) {
		BigDecimal daymoney = new BigDecimal(drugtotal);
		DayAccount day = new DayAccount();
		day.setAccount(null);
		day.setDayMoney(daymoney);
		day.setDayOpreator(dayOpreator);
		daydao.save(day);
		
		System.out.println("日结单的主键："+day.getDayId());
		//修改病程记录中的日结单外键
		String array[] =arr.split(",");
		if(!"".equals(arr)) {
			for(int i=0;i<array.length;i++) {
				illmapper.updateNessRecordDay(day.getDayId(),
						Integer.parseInt(array[i]));
			}
		}
		
	}
	
	//新增床位
	public void AddBed(String bedNo,BigDecimal bedMoney,Integer sickroomName) {		
		//根据病房id查询
		SickRoom room = roomdao.findById(sickroomName).get();
		Bed b = new Bed();
		b.setBedNo(bedNo);
		b.setBedMoney(bedMoney);
		b.setSickRoom(room);
		b.setBedState(0);
		bdao.save(b);
		//判断病房是否满床位，如果满了就修改病房的状态
		JSONArray roomFull = bmapper.selectBedRoomFull();
		if(roomFull != null) {
			//修改病房的状态
			roommapper.updateRoomState(room.getSickroomId());
		}
	}
	
	//扣除每天住院的床位租金
	public String deduckCashmoney(String hospid,BigDecimal money) {
		//根据住院号查询
		InhospitalReg reg = regdao.findById(hospid).get();
		//根据住院号查询押金
		CashMoney cashMoney = mdao.findCashmoneyBihospid(hospid);
		//修改押金表的押金余额
		CashMoney m = new CashMoney();
		m.setCashId(cashMoney.getCashId());
		m.setInhospitalReg(reg);
		//修改押金表的余额，扣除床位租金的金额（用押金余额-租金）
		BigDecimal  dmoney = cashMoney.getCashDmoney().subtract(money);
		m.setCashDmoney(dmoney);
		m.setCashTotalmoney(cashMoney.getCashTotalmoney());
		m.setCashOperatorName(cashMoney.getCashOperatorName());
		mdao.save(m);
		return "扣除押金成功";
	}
	
	//调整床位
	public void addChangeBed(String hospId,Integer oldbedId,Integer newbedId,String bedchangePeople) {
		//根据住院号查询
		InhospitalReg inhospitalReg = regdao.findById(hospId).get();
		//根据住院号查询旧床位的主键，且修改床位状态为没人（得到旧床位号的主键来修改状态）
		Bed oldbed = bdao.findById(oldbedId).get();
		//修改旧床位的信息(作为调整的记录)
		Bed bb = new Bed();
		bb.setBedId(oldbed.getBedId());
		bb.setInhospitalReg(inhospitalReg);
		bb.setBedNo(oldbed.getBedNo());
		bb.setSickRoom(oldbed.getSickRoom());
		bb.setBedMoney(oldbed.getBedMoney());
		bb.setBedchangePeople(bedchangePeople);
		bb.setBedState(2);//修改状态
		bdao.save(bb);
		
		//根据床位主键查询床位号[新的床位号]
		Bed bybedid = bdao.findById(newbedId).get();
		String new_bedNo =  bybedid.getBedNo();
		BigDecimal bedmoney = bybedid.getBedMoney();
		Integer roomid = bybedid.getSickRoom().getSickroomId();
		//根据病房主键查询
		SickRoom sickRoom = roomdao.findById(roomid).get();
				
		//调整一条新的床位记录(完善床位的信息)
		Bed b = new Bed();
		b.setBedId(newbedId);
		b.setInhospitalReg(inhospitalReg);
		b.setBedNo(new_bedNo);
		b.setBedState(1);//床位状态修改为有人
		b.setSickRoom(sickRoom);
		b.setBedMoney(bedmoney);
		b.setBedchangeTime(null);
		b.setBedchangePeople(bedchangePeople);
		bdao.save(b);
				
				
		//且新增一条新的床位（床位号为调整床位的旧床位号）
		Bed bbb = new Bed();
		bbb.setBedNo(oldbed.getBedNo());
		bbb.setSickRoom(sickRoom);
		bbb.setBedState(0);//修改状态为没人
		bbb.setBedMoney(new BigDecimal(120));
		bdao.save(bbb);
		
		//根据住院号查询押金
		CashMoney cashMoney = mdao.findCashmoneyBihospid(hospId);
		//获取押金id
		Integer cashmoneyid = cashMoney.getCashId();
		//获取押金余额
		BigDecimal cmoney=cashMoney.getCashDmoney();
		//获取总押金
		BigDecimal totalmoney = cashMoney.getCashTotalmoney();
		//修改押金表的押金余额
		CashMoney m = new CashMoney();
		m.setCashId(cashmoneyid);
		m.setInhospitalReg(inhospitalReg);
		//修改押金表的余额，扣除床位租金的金额（用押金余额-租金）
		BigDecimal  money = cmoney.subtract(bedmoney);
		m.setCashDmoney(money);
		m.setCashTotalmoney(totalmoney);
		m.setCashOperatorName(bedchangePeople);
		mdao.save(m);
		
	}
	
	//住院和床位表联合查询(得到所搜的信息)
	public JSONArray selectChangeBedByhospid(String hospid) {
		return bmapper.selectChangeBedByhospid(hospid);
	}
	
	//查询调整记录
	public JSONArray selectChangeBedBybedid(String hospid) {
		return bmapper.selectChangeBedAllBybedid(hospid);
	}
	
	
	
	/*
	 * 
	 * 
	 * 收费管理的功能
	 * 
	 * 
	 * */
	
	//结算的确定按钮（新增return_money表）
	public void AddFeeList(String hospId,BigDecimal returnmoneyMoney,Integer status) {
		//根据住院id查询
		InhospitalReg inhospitalReg = regdao.findById(hospId).get();
		
		//新增退费表（状态为2时，是出院时的总消费记录）
		ReturnMoney rm = new ReturnMoney();
		rm.setInhospitalReg(inhospitalReg);//住院号
		rm.setReturnmoneyMoney(returnmoneyMoney);//押金金额
		rm.setReturnmoneyState(status);
		rm.setReturnmoneyTime(null);
		rdao.save(rm);
		
		if(status==-1) {
			//把押金余额修改为零
			CashMoney cashMoney = mdao.findCashmoneyBihospid(hospId);
			//修改押金表的押金余额
			CashMoney m = new CashMoney();
			m.setCashId(cashMoney.getCashId());
			m.setInhospitalReg(inhospitalReg);
			m.setCashTotalmoney(cashMoney.getCashTotalmoney());
			m.setCashDmoney(new BigDecimal(0));
			m.setCashOperatorName(cashMoney.getCashOperatorName());
			mdao.save(m);
		}
		

		if(status==3) {
			//把押金余额修改为零
			CashMoney cashMoney = mdao.findCashmoneyBihospid(hospId);
			//修改押金表的押金余额
			CashMoney m = new CashMoney();
			m.setCashId(cashMoney.getCashId());
			m.setInhospitalReg(inhospitalReg);
			m.setCashTotalmoney(cashMoney.getCashTotalmoney());
			m.setCashDmoney(new BigDecimal(0));
			m.setCashOperatorName(cashMoney.getCashOperatorName());
			mdao.save(m);
		}
		
		
		
	}
	
	//查询住院期间的交费的记录
	public JSONArray selectReturnMoneyAll() {
		return rmapper.selectReturnMoneyAll();
	}
	
	//查询费用清单
	public JSONArray selectfeelist(String hospid) {
		return daymapper.selectFeeList(hospid);
	}
	
	//查询退费的记录
	public JSONArray selectReturnFeeAll() {
		return rmapper.selectReturnFeeAll();
	}
	
	/*
	 * 
	 * 出院的功能
	 * 
	 * */
	
	//新增出院表
	public void AddOutHosptails(String hospId,BigDecimal outTotalmoney,
			String outOpreator,String outAdvice,Integer bedid) {
		//根据住院id查询
		InhospitalReg inhospitalReg = regdao.findById(hospId).get();
		
		OutHospital out = new OutHospital();
		out.setInhospitalReg(inhospitalReg);
		out.setOutAdvice(outAdvice);
		out.setOutOpreator(outOpreator);
		out.setOutTotalmoney(outTotalmoney);
		outdao.save(out);
		
		//修改床位表的状态为2
		//根据住院号查询旧床位的主键，且修改床位状态为没人（得到旧床位号的主键来修改状态）
		Bed oldbed = bdao.findById(bedid).get();
		
		//修改旧床位的信息
		Bed bb = new Bed();
		bb.setBedId(oldbed.getBedId());
		bb.setInhospitalReg(inhospitalReg);
		bb.setBedNo(oldbed.getBedNo());
		bb.setSickRoom(oldbed.getSickRoom());
		bb.setBedMoney(oldbed.getBedMoney());
		bb.setBedchangePeople(oldbed.getBedchangePeople());
		bb.setBedState(2);//修改状态
		bdao.save(bb);
	}
	
	//查询出院的记录
	public JSONArray selectOutHospRecord() {
		return hmap.selectOutHospRecord();
	}
	
	/*
	 * 
	 * 手术台的功能
	 * 
	 * */
	
	
	//新增手术项目
	public void addOpreationtype(Integer operationroomId,
		    String operationtypeName,BigDecimal operationroomPrice) {		
		anmapper.AddOperationType(operationtypeName,operationroomId,operationroomPrice);
    }
	
	//查询未进行手术的手术安排(初始化表格)
	public JSONArray selectArrangeStatusAll() {
		return anmapper.selectArrangeStatusAll();
	}
	
	//根据主键修改手术安排的状态(用于取消手术安排)
	public void updateArrangeStatus(Integer operationstate,
			Integer operationid,BigDecimal oparrange_money,String hosp_id) {
		
		//修改手术的状态为-1
		anmapper.updatearrangestatus(operationstate, operationid);
		//手术安排中的预估金额扣除为0
		anmapper.updatearrangemoney(operationid);

		InhospitalReg inhospitalReg = regdao.findById(hosp_id).get();
		//扣除押金
		CashMoney cashMoney = mdao.findCashmoneyBihospid(hosp_id);
	    //修改押金表的押金余额
		CashMoney m = new CashMoney();
		m.setCashId(cashMoney.getCashId());
		m.setInhospitalReg(inhospitalReg);
		m.setCashTotalmoney(cashMoney.getCashTotalmoney());
		//押金余额加
		BigDecimal  money = cashMoney.getCashDmoney().add(oparrange_money);
		m.setCashDmoney(money);
		m.setCashOperatorName(cashMoney.getCashOperatorName());
		mdao.save(m);
	}
	
	//新增手术记录
	public void AddOpsingRecord(Integer operationId,String opRecordPeople,
			String opRecordBegintime,String opRecordEndtime,BigDecimal opRecordMoney) {		
		//查询手术安排
		OperationArrange arraygeByid = andao.findById(operationId).get();
		
		//新增手术记录
		OperationRecord re = new OperationRecord();
		re.setOperationArrange(arraygeByid);
		re.setOpRecordBegintime(null);
		re.setOpRecordEndtime(null);
		re.setOpRecordMoney(opRecordMoney);
		re.setOpRecordPeople(opRecordPeople);
		
	    redao.save(re);
		
		//修改手术安排的状态
	    anmapper.updatearrangestatus(1, operationId);
	    
	  //扣除押金
//	  		CashMoney cashMoney = mdao.findCashmoneyBihospid(hosp_id);
//	  	    //修改押金表的押金余额
//	  		CashMoney m = new CashMoney();
//	  		m.setCashId(cashMoney.getCashId());
//	  		m.setInhospitalReg(inhospitalReg);
//	  		m.setCashTotalmoney(cashMoney.getCashTotalmoney());
//	  		//押金余额加
//	  		BigDecimal  money = cashMoney.getCashDmoney().add(oparrange_money);
//	  		m.setCashDmoney(money);
//	  		m.setCashOperatorName(cashMoney.getCashOperatorName());
//	  		mdao.save(m);
		
	}
	
	//查询手术记录(初始化记录表格)
	public JSONArray  selectRecordAll() {
		return anmapper.selectRecordAll();
	}
	
	
	/*
	 * 体检的功能的方法
	 * 
	 * */
	
	//查询所有的体检项目
	public JSONArray selectHealAll(){
		return hmapper.selectByHealAll();
	}
	
	//查询体检套餐
	public JSONArray selectMealProjectAll() {
		return hmapper.selectMealProjectAll();
	}
	
	//根据套餐查询具体的项目
	public JSONArray selectMealProjectByid(Integer mno) {
		return hmapper.selectMealProjectByid(mno);
	}
	
	
	//新增体检【住院开立体检】
	public void AddHealth(String hospId,String project_arr,String totalmoney,
			Integer projectno,Integer lookillnessid,
			Integer clinicid,Integer healthmoneystatus,Integer healthtype) {
		
		//根据住院号查询，获取医疗卡主键
	    InhospitalReg inhospitalReg = regdao.findById(hospId).get();
		Integer cid = inhospitalReg.getClinicCard().getClinicId();
		
		//计算体检项目的总金额（用押金表中余额-项目总金额）
		CashMoney money = mdao.findCashmoneyBihospid(hospId);
		//获取押金表的押金余额
		BigDecimal cmoney =	money.getCashDmoney();
		//体检总金额
		BigDecimal heamoney = new BigDecimal(totalmoney);
		//计算押金余额
		BigDecimal cm = cmoney.subtract(heamoney);
		//获取押金主键
		Integer cashmoneyid = money.getCashId();
		CashMoney c_entity = mdao.findById(cashmoneyid).get();
		//修改押金表的余额
		c_entity.setCashDmoney(cm);
		
		//分割体检项目编号
		String arr[] =project_arr.split(",");
		if(!"".equals(project_arr)) {
			for(int i=0;i<arr.length;i++) {
				hmapper.AddHealth(Integer.parseInt(arr[i]),lookillnessid, 
						cid, healthmoneystatus,healthtype);

			}
		}
		
		
	}
	
	
	//新增体检预约【新增医疗卡，开立体检】AppointmentVo
	public String AddHealthOppoint2(AppointmentVo avo) {
		ClinicCard clinicCard = ccdao.save(avo.getClinic());
		List<HealthProject> project = avo.getProject();
		List<HealthMeal> meal = avo.getMeal();
		//套餐
		if(project == null) {
			for (HealthMeal hm : meal) {
				HealthAppointment appoint = new HealthAppointment();
				appoint.setClinicCard(clinicCard);
				appoint.setAppoStatus(avo.getAppoint().getAppoStatus());
				appoint.setAppoPeople(avo.getAppoint().getAppoPeople());
				appoint.setHealthProject(null);
				appoint.setHealthMeal(hm);
				apdao.save(appoint);
			}
			return "开立套餐成功";
		}
		
		//单个项目
		if(meal == null) {
			for (HealthProject hp : project) {
				HealthAppointment appoint = new HealthAppointment();
				appoint.setClinicCard(clinicCard);
				appoint.setAppoStatus(avo.getAppoint().getAppoStatus());
				appoint.setAppoPeople(avo.getAppoint().getAppoPeople());
				appoint.setHealthProject(hp);
				appoint.setHealthMeal(null);
				apdao.save(appoint);
			}
			return "开立单个项目成功";
		}
		return "成功";	
	}
	
	public void AddHealthOppoint(String clinicName,String cliniccardId, 
			String clinicIdnumber,Integer clinicAge,
			String clinicTel,String clinicHandlename,
			BigDecimal clinicRemainmoney, String clinicSex,
			Integer status,String arr,String totalmoney) {
		//新增医疗卡
		ClinicCard c = new ClinicCard();
		c.setCliniccardId(cliniccardId);
		c.setClinicIdnumber(clinicIdnumber);
		c.setClinicName(clinicName);
		c.setClinicAge(clinicAge);
		c.setClinicSex(clinicSex);
		c.setClinicTel(clinicTel);
		c.setClinicHandlename(clinicHandlename);
		c.setClinicRemainmoney(clinicRemainmoney);//医疗卡得金额
		c.setClickState(status);
		
		ccdao.save(c);
		
		//新增体检预约表
		String array[] =arr.split(",");
		if(!"".equals(arr)) {
			for(int i=0;i<array.length;i++) {
				hmapper.AddHealthAppoint(c.getClinicId(), Integer.parseInt(array[i]),
						null,clinicHandlename, 0);
				
			}
		}
	}
	
	//查询自主体检的记录
	public JSONArray selectHealthAppointAll(String name) {
		return hmapper.selectHealthAppointAll(name);
	}
	
	//体检查看详情体检项目
	public JSONArray selectHealthAppointDetials(Integer clinicid) {
		return hmapper.selectHealthAppointDetials(clinicid);
	}
	
	//自主新增体检检查
	public String AddHealthOwn(JSONArray array) {
		
		for (int i = 0; i < array.size(); i++) {
			Integer cid = (Integer) array.getJSONObject(i).get("cid");
			Integer pno = (Integer) array.getJSONObject(i).get("project_no");
			Integer hid = (Integer) array.getJSONObject(i).get("Health_no");
			String result = "" + array.getJSONObject(i).get("health_result");
			//获取医疗卡
			ClinicCard clinic = ccdao.findById(cid).get();
			HealthProject project = hpdao.findById(pno).get();
			Health health = hdao.findbyHealthId(hid);
			Health h = new Health();
			//修改体检结果
			if(health != null) {
				h.setHealthNo(hid);
				h.setClinicCard(clinic);
				h.setHealthProject(project);
				h.setHealthResult(result);
				hdao.save(h);
				
				return "门诊住院体检成功";
			}
			//新增体检记录
			if(health == null) {
				h.setClinicCard(clinic);
				h.setHealthProject(project);
				h.setHealthResult(result);
				h.setHealthMoneyStatus(1);
				hdao.save(h);
				if(result != null) {
					//修改体检预约的状态
					hmapper.updateAppointSatus(cid);
				}
				return "预约体检成功";
			}
		}
/*	    //获取医疗卡
		ClinicCard clinic = ccdao.findById(hvo.getClinic().getClinicId()).get();
	
		List<HealthProject> healpro = hvo.getHealthproject();
		System.out.println("项目编号："+hvo.getHealthproject().get(0));
		
		for (HealthProject hpp : healpro) {

			Health health = hdao.findbyHealthId(hvo.getHealth().getHealthNo());
			Health h = new Health();
			
			HealthProject project = hpdao.findById(hpp.getProjectNo()).get();
			
			//修改体检结果
			if(health != null) {
				h.setHealthNo(hvo.getHealth().getHealthNo());
				System.out.println("门诊住院体检号："+hvo.getHealth().getHealthNo());
				h.setClinicCard(clinic);
				h.setHealthProject(project);
				hdao.save(h);
				return "门诊住院体检失败";
			}
			//新增体检记录
			if(health == null) {
				System.out.println("自主检号：");
				h.setClinicCard(clinic);
				h.setHealthProject(project);
				h.setHealthResult(hvo.getHealth().getHealthResult());
				h.setHealthMoneyStatus(1);
				hdao.save(h);
				
				System.out.println("体检结果："+hvo.getHealth().getHealthResult());
				if(hvo.getHealth().getHealthResult() != null) {
					//修改体检预约的状态
					hmapper.updateAppointSatus(hvo.getClinic().getClinicId());
				}

				return "预约体检失败";
			}
		}*/
		
		return "体检";
	}
	
	
	
	//查询门诊，住院的体检信息
	public JSONArray selectHealTwoRecordAll() {
		return hmapper.selectHealTwoRecordAll();
	}
		
	//门诊，住院体检的详情体检项目
	public JSONArray selectHealTwoRecordDetils(Integer clinicid) {
		return hmapper.selectHealTwoRecordDetils(clinicid);
	}

	//查询体检报告
	public JSONArray selectHealthproAll() {
		return hmapper.selectHealthproAll();
	}
	
	//新增体检项目
	public void AddhealthProject(String projectName,String projectPrice,
			Integer projectNo,Integer sectionId) {
		
		BigDecimal price = new BigDecimal(projectPrice);
		//根据科室id查询
		Section section = sedao.findById(sectionId).get();
		HealthProject hp = new HealthProject();
		if(projectNo==null) {
			hp.setProjectPrice(price);
			hp.setProjectName(projectName);
			hp.setSection(section);
			hpdao.save(hp);
		}else {
			hp.setProjectNo(projectNo);
			hp.setProjectPrice(price);
			hp.setProjectName(projectName);
			hp.setSection(section);
			hpdao.save(hp);
		}

	}
	
	public JSONArray selectHealBysid (/*String sectionname,*/String projectname){
		return hmapper.selectHealBysid(/*sectionname, */projectname);
	}
}
